package cn.getech.data.development.service.impl;

import cn.getech.data.development.entity.TableRelationshipEntity;
import cn.getech.data.development.model.res.tableinfo.TableRelationshipField;
import cn.getech.data.development.model.res.tableinfo.TableRelationshipRes;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.getech.data.intelligence.common.utils.PageUtils2;
import cn.getech.data.intelligence.common.utils.Query;

import cn.getech.data.development.mapper.TableRelationshipMapper;
import cn.getech.data.development.service.TableRelationshipService;


@Service("tableRelationshipService")
public class TableRelationshipServiceImpl extends ServiceImpl<TableRelationshipMapper, TableRelationshipEntity> implements TableRelationshipService {

    @Override
    public PageUtils2<TableRelationshipEntity> queryPage(Map<String, Object> params) {
        IPage<TableRelationshipEntity> page = this.page(
                new Query<TableRelationshipEntity>().getPage(params),
                new QueryWrapper<TableRelationshipEntity>()
        );

        return new PageUtils2<TableRelationshipEntity>(page);
    }

    @Override
    public TableRelationshipRes bloodRelation(Integer id) {
        List<TableRelationshipEntity> relationshipEntities = list(new QueryWrapper<TableRelationshipEntity>().eq("source_table_id", id));
        if(CollectionUtil.isEmpty(relationshipEntities))
            return null;

        TableRelationshipRes res = new TableRelationshipRes();
        res.setTableName(relationshipEntities.get(0).getSourceTableName());

        List<TableRelationshipField> fields = new ArrayList<>();
        res.setFields(fields);
        Map<String, List<TableRelationshipEntity>> collect = relationshipEntities.stream().collect(Collectors.groupingBy(TableRelationshipEntity::getSourceFieldName));
        for(String fieldName : collect.keySet()){
            TableRelationshipField field = new TableRelationshipField();
            field.setFieldName(fieldName);
            field.setRelationes(collect.get(fieldName));
            fields.add(field);
        }

        return res;
    }


}
